import os
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.ticker as mick
import datetime

# 字体导入
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['font.size'] = 15

def feature_analyse1(path):
    # 4,5,7,10（NumCompaniesWorked（曾工作过的公司数量），PercentSalaryHike（薪资涨幅百分比），TrainingTimesLastYear（去年参加的培训次数），YearsSinceLastPromotion（自上次晋升以来的年限））
    # 设置显示选项，取消列数和行数的限制
    pd.set_option('display.max_columns', None)  # 显示所有列
    pd.set_option('display.max_rows', None)  # 显示所有行
    pd.set_option('display.width', None)  # 自动调整宽度以适应屏幕
    pd.set_option('display.max_colwidth', None)  # 显示完整的列内容
    data = pd.read_csv(path)
    left = data[data['Attrition'] == 1]
    stayed = data[data['Attrition'] == 0]
    num_features = ["Age", "DistanceFromHome", "MonthlyIncome", "NumCompaniesWorked", "PercentSalaryHike", "TotalWorkingYears", "TrainingTimesLastYear", "YearsAtCompany", "YearsInCurrentRole", "YearsSinceLastPromotion", "YearsWithCurrManager"]
    ch_num_features = ['年龄','家与工作地点的距离','月收入','曾工作过的公司数量','薪资涨幅百分比','绩效评级','去年参加的培训次数','在公司工作的年限','在当前岗位工作的年限','自上次晋升以来的年限','与当前经理共事的年限']
    print("【离职组 - 数值特征描述】")
    print(left[num_features].describe())
    print("\n【未离职组 - 数值特征描述】")
    print(stayed[num_features].describe())
    for i in range(len(num_features)):
        plt.figure(figsize=(8, 5))
        sns.boxplot(x='Attrition', y=num_features[i], data=data)
        plt.title(f'{ch_num_features[i]}的箱线图')
        plt.savefig(f"../data/fig/特征分析/{ch_num_features[i]}的箱线图.png")
        plt.show()

def feature_analyse2(path):
    # 删掉性别列
    data = pd.read_csv(path)
    # left = data[data['Attrition'] == 1]
    # stayed = data[data['Attrition'] == 0]
    cat_features_nominal = ['BusinessTravel', 'Department', 'OverTime',"EducationField", "Gender", "JobRole", "MaritalStatus"]
    ch_cat_features_nominal = ['商务旅行情况',"部门","是否加班","教育领域","性别","工作角色","婚姻状况"]
    for i in range(len(cat_features_nominal)):
        # 计算每个类别下的离职率
        prop_table = pd.crosstab(data[cat_features_nominal[i]], data['Attrition'], normalize='index') * 100
        prop_table.plot(kind='bar', stacked=True, figsize=(10, 7))
        plt.title(f'{ch_cat_features_nominal[i]}的离职率')
        plt.xticks(rotation=20,fontsize=8)
        plt.xlabel('')
        plt.ylabel('Percentage')
        plt.legend(title='Attrition', loc='upper right')
        plt.savefig(f"../data/fig/特征分析/{ch_cat_features_nominal[i]}的离职率.png")
        plt.show()


def feature_analyse3(path):
    data = pd.read_csv(path)
    cat_features_ordinal = ['Education','JobSatisfaction', 'EnvironmentSatisfaction', 'WorkLifeBalance', 'RelationshipSatisfaction','JobInvolvement','PerformanceRating','JobLevel','StockOptionLevel']
    ch_cat_features_ordinal = ['教育程度','工作满意度',"工作环境满意度","工作与生活平衡度",'人际关系满意度','工作投入度','绩效评级','工作级别','股票期权水平']
    for i in range(len(cat_features_ordinal)):
        # 计算每个满意度等级下的离职率
        satisfaction_attrition = data.groupby(cat_features_ordinal[i])['Attrition'].mean() * 100
        satisfaction_attrition.plot(kind='bar', figsize=(10, 6))
        plt.title(f'{ch_cat_features_ordinal[i]}各个等级的离职率')
        plt.ylabel('离职率(%)')
        plt.xlabel(ch_cat_features_ordinal[i])
        plt.savefig(f"../data/fig/特征分析/{ch_cat_features_ordinal[i]}各个等级的离职率.png")
        plt.show()



if __name__ == '__main__':
    path = "../data/processed/test_aligned.csv"
    # feature_analyse1(path)
    # feature_analyse2(path)
    feature_analyse3(path)
    # df = pd.read_csv(path)
    # data = df.copy()
    # data.BusinessTravel = data.BusinessTravel.map({'Travel_Rarely': 1, 'Travel_Frequently': 2, 'Non-Travel': 0})
    # data.MaritalStatus = data.MaritalStatus.map({'Divorced': 2, 'Single': 0, 'Married': 1})
    # onehot = pd.get_dummies(data[['Department', 'EducationField', 'JobRole', 'OverTime']])
    # data = pd.concat([data, onehot], axis=1)
    # data = data.drop(columns=["NumCompaniesWorked","PercentSalaryHike",'TrainingTimesLastYear','YearsSinceLastPromotion','Gender','EmployeeNumber','Over18','StandardHours','Department', 'EducationField', 'JobRole', 'OverTime','OverTime_No'])
    # print(data.columns)
    # feature_name = data.loc[:,'Age':"OverTime_Yes"].columns.to_list()
    # feature_name.remove('Attrition')
    # print(len(feature_name))
    # # print(feature_name)
    # data['RoleStagnationPeriod'] = data['YearsInCurrentRole'] / (data['YearsAtCompany'] + 10 ** -5)  # 保留
    # data['ManagerPeriod'] = data['YearsWithCurrManager'] / (data['YearsAtCompany'] + 10 ** -5)  # 保留
    # data['IncomeCompetitionRate'] = data['MonthlyIncome'] / (data['TotalWorkingYears'] + 10 ** -5)  # 保留
    # data['AgeWorkingRate'] = data['Age'] / (data['TotalWorkingYears'] + 10 ** -5)
    # feature_name = feature_name+['RoleStagnationPeriod',"ManagerPeriod","IncomeCompetitionRate","AgeWorkingRate"]
    # # data.info()
    # print(len(feature_name))
    # x = data[feature_name]
    # y = data['Attrition']
    # # print(x)
    # # print(y)
    # data_final = pd.concat([x,y],axis=1)
    # print(data_final)
    # data_final.to_csv("../data/processed/test_final2.csv")
